package com.fjp.heartguard.app.network

import android.content.Intent
import android.util.Log
import androidx.core.content.ContextCompat.startActivity
import com.fjp.heartguard.app.eventViewModel
import com.fjp.heartguard.app.util.CacheUtil
import com.fjp.heartguard.ui.login.LoginActivity
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.util.toJson
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException


/**
 *
 * 时间　: 2022/1/13
 * 描述　: token过期拦截器
 */
class TokenOutInterceptor : Interceptor {

    val gson: Gson by lazy { Gson() }

    @kotlin.jvm.Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        Log.d("===request:", chain.request().toJson())
        val response = chain.proceed(chain.request())
        return if (response.body() != null && response.body()!!.contentType() != null) {
            val mediaType = response.body()!!.contentType()
            val string = response.body()!!.string()
            Log.d("===response:", string)
            val responseBody = ResponseBody.create(mediaType, string)
            try {
                val apiResponse = gson.fromJson(string, ApiResponse::class.java)
                //判断逻辑 模拟一下
                if (apiResponse.code == 401) {
                    Log.d("执行了401", "=====================")
                    CacheUtil.setUser(null)
                    //如果是普通的activity话 可以直接跳转，如果是navigation中的fragment，可以发送通知跳转
                   val intent =  Intent(appContext, LoginActivity::class.java)
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    appContext.startActivity(intent)

                }else if(apiResponse.code == 403){
                    eventViewModel.noPermission.postValue(true)
                }
            } catch (e: Exception) {
                println("Gson 解析异常")
            }

            response.newBuilder().body(responseBody).build()
        } else {
            response
        }
    }
}